package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.ItemVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class ItemServiceImpl implements  ItemService<Item> {

    @Autowired
    private ItemMapper<Item>  itemMapper;

    @Autowired
    private ItemDescMapper  itemDescMapper;

    @Override
    public PageResult getItemPage(PageResult pageResult) {
        IPage  page=new Page();
        page.setPages(pageResult.getPageSize());
        page.setCurrent(pageResult.getPageNum());
        QueryWrapper<Item>  queryWrapper=new QueryWrapper();
        String query = pageResult.getQuery();
        boolean b = StringUtils.hasLength(query);
        queryWrapper.like(b,"title",pageResult.getQuery());
        IPage iPage = itemMapper.selectPage(page, queryWrapper);
        pageResult.setTotal(iPage.getTotal());
        pageResult.setRows(iPage.getRecords());
        return   pageResult;
    }

    @Override
    public boolean deleteById(Integer id) {
        //删除item的同时也要将itemDesc进行删除
        itemMapper.deleteById(id);
        itemDescMapper.deleteById(id);
        return  true;
    }

    @Override
    public boolean updateItemById(Item item) {
        item.setUpdated(new Date());
        int i = itemMapper.updateById(item);
        return  (i==1);
    }

    @Override
    @Transactional
    public void saveItem(ItemVO  itemVO) {
        Item item = itemVO.getItem();
        itemMapper.insert(item);
        ItemDesc itemDesc = itemVO.getItemDesc();
        itemDesc.setId(item.getId());
        itemDescMapper.insert(itemDesc);

    }
}
